/**
 * 响应模型接口
 */
export interface ResponseModel {
  status: number;
  statusText: string;
  headers: Record<string, string>;
  body: any;
  time: number;
}

/**
 * 响应模型类
 */
export class Response implements ResponseModel {
  status: number;
  statusText: string;
  headers: Record<string, string>;
  body: any;
  time: number;

  /**
   * 构造函数
   * @param data 响应数据
   */
  constructor(data: Partial<ResponseModel> = {}) {
    this.status = data.status || 0;
    this.statusText = data.statusText || '';
    this.headers = data.headers || {};
    this.body = data.body || null;
    this.time = data.time || 0;
  }

  /**
   * 检查响应是否成功
   * @returns 是否成功
   */
  isSuccess(): boolean {
    return this.status >= 200 && this.status < 300;
  }

  /**
   * 从Fetch API响应创建响应对象
   * @param response Fetch API响应
   * @param body 响应体
   * @param time 响应时间
   * @returns 响应对象
   */
  static async fromFetchResponse(response: globalThis.Response, body: any, time: number): Promise<Response> {
    const headers: Record<string, string> = {};
    response.headers.forEach((value, key) => {
      headers[key] = value;
    });

    return new Response({
      status: response.status,
      statusText: response.statusText,
      headers,
      body,
      time
    });
  }

  /**
   * 格式化响应体
   * @returns 格式化后的响应体
   */
  formatBody(): string {
    if (!this.body) return '';

    try {
      if (typeof this.body === 'string') {
        // 尝试解析JSON
        try {
          const parsed = JSON.parse(this.body);
          return JSON.stringify(parsed, null, 2);
        } catch {
          return this.body;
        }
      } else if (typeof this.body === 'object') {
        return JSON.stringify(this.body, null, 2);
      } else {
        return String(this.body);
      }
    } catch (error) {
      return `Error formatting response: ${error}`;
    }
  }

  /**
   * 获取内容类型
   * @returns 内容类型
   */
  getContentType(): string {
    const contentType = this.headers['content-type'] || '';
    if (contentType.includes('application/json')) {
      return 'json';
    } else if (contentType.includes('text/html')) {
      return 'html';
    } else if (contentType.includes('text/xml') || contentType.includes('application/xml')) {
      return 'xml';
    } else if (contentType.includes('text/')) {
      return 'text';
    } else {
      return 'unknown';
    }
  }

  /**
   * 序列化为JSON
   * @returns JSON对象
   */
  toJSON(): ResponseModel {
    return {
      status: this.status,
      statusText: this.statusText,
      headers: this.headers,
      body: this.body,
      time: this.time
    };
  }
}

/**
 * 确保响应对象具有正确的原型链
 * @param responseData 响应数据
 * @returns 响应对象
 */
export function ensureResponseInstance(responseData: any): Response {
  if (responseData instanceof Response) {
    return responseData;
  }
  return new Response(responseData);
} 